﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace LogCat.Utility
{
    class StringParseUtility
    {
        public enum EncodeType 
        { 
           GBK,
           UTF8
        }
        
        static string Tag = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;

        public delegate void ProcessData(Match match);

        //处理文件
        public static bool ParseFile(string path,ProcessData dele)
        {
            StreamReader sr = null;
            try
            {
                sr = File.OpenText(path);

                string line, buffer = "";
                int bufferLine = 0;

                while ((line = sr.ReadLine()) != null)
                {
                    buffer += ToUTF8(line);

                    //如果累计了100行还没有找到要处理的文本，就认为文件错误
                    if (++bufferLine > 100) throw new Exception("100行内找不到所需内容，终止处理!");

                    Match mt = new Regex(ConfigUtility.config.log_rule).Match(buffer);
                    if (mt.Success)
                    {
                        buffer = "";
                        bufferLine = 0;
                        dele(mt);
                    }
                }
            }
            catch (Exception e)
            {
                Log.i(Tag, e.Message);
                return false;
            }
            finally
            {
                if(sr != null) sr.Close();
            }

            return true;
        }

        //将字符串装成UTF-8格式
        private static string ToUTF8(string str){
            switch(ConfigUtility.encode)
            {
                case EncodeType.GBK://这里转换有问题
                    byte[] bytes = Encoding.GetEncoding("gb2312").GetBytes(str);
                    byte[] temp = Encoding.Convert(Encoding.GetEncoding("gb2312"), Encoding.UTF8, bytes);
                    str = Encoding.UTF8.GetString(temp);
                    break;
            }

            return str;
        }
    }
}
